/**
 * main.js - 终端初始化和WebSocket连接管理
 */

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', () => {
  // 初始化终端
  const term = new CanvasTerminal({
    cursorBlink: true,
    fontSize: 14,
    fontFamily: '"Microsoft YaHei", "微软雅黑", "Noto Sans CJK SC", "Source Han Sans SC", "Source Han Sans CN", "WenQuanYi Micro Hei", Monaco, "Menlo", "Ubuntu Mono", monospace',
    foreground: '#ECECEC',
    background: '#000000',
    cursorColor: '#FFFFFF'
  });

  // 打开终端
  term.open(document.getElementById('terminal-container'));

  // 调整终端尺寸以适应容器
  term.fit();

  // WebSocket 连接管理
  let socket = null;
  const statusIndicator = document.getElementById('status-indicator');
  const statusText = document.getElementById('status-text');

  function connectWebSocket() {
    // 更新连接状态
    statusIndicator.className = 'connection-status connecting';
    statusText.textContent = '连接中...';

    // 获取当前主机和端口，构建 WebSocket URL
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${window.location.host}/ws`;

    try {
      socket = new WebSocket(wsUrl);

      socket.onopen = function() {
        statusIndicator.className = 'connection-status connected';
        statusText.textContent = '已连接';
        term.write('\r\n\x1b[32mCanvas Terminal 连接成功!\x1b[0m\r\n');
        term.write('\x1b[33m$\x1b[0m ');
      };

      socket.onmessage = function(event) {
        term.write(event.data);
      };

      socket.onclose = function(event) {
        statusIndicator.className = 'connection-status disconnected';
        statusText.textContent = '已断开连接';

        if (event.wasClean) {
          term.write('\r\n\x1b[33m连接已关闭\r\n\x1b[0m');
        } else {
          term.write('\r\n\x1b[31m连接异常断开\r\n\x1b[0m');
        }

        // 5秒后尝试重连
        setTimeout(connectWebSocket, 5000);
      };

      socket.onerror = function(error) {
        statusIndicator.className = 'connection-status disconnected';
        statusText.textContent = '连接错误';
        term.write('\r\n\x1b[31mWebSocket 错误: ' + error + '\x1b[0m\r\n');
      };

    } catch (error) {
      term.write('\r\n\x1b[31m创建 WebSocket 连接时出错: ' + error.message + '\x1b[0m\r\n');
      // 5秒后尝试重连
      setTimeout(connectWebSocket, 5000);
    }
  }

  // 处理终端输入
  term.onData(function(data) {
    if (socket && socket.readyState === WebSocket.OPEN) {
      socket.send(data);
    } else {
      term.write('\r\n\x1b[31m未连接到服务器，无法发送命令\x1b[0m\r\n');
    }
  });

  // 处理窗口大小变化
  window.addEventListener('resize', () => {
    term.fit();

    // 通知后端终端尺寸变化（如果需要的话）
    if (socket && socket.readyState === WebSocket.OPEN) {
      // 可以发送尺寸信息给后端，例如:
      // socket.send(JSON.stringify({type: 'resize', cols: term.options.cols, rows: term.options.rows}));
    }
  });

  // 初始化连接
  connectWebSocket();

  // 添加欢迎信息
  setTimeout(() => {
    term.write('\r\n\x1b[36m欢迎使用 Canvas Terminal!\x1b[0m\r\n');
    term.write('\x1b[2;3m这是一个基于 Canvas 和 Go 的浏览器终端模拟器\x1b[0m\r\n\r\n');
  }, 100);
});